package cn.wolfcode.car.realm;

import cn.wolfcode.car.domain.Employee;
import cn.wolfcode.car.service.IEmployeeService;
import cn.wolfcode.car.service.IPermissionService;
import cn.wolfcode.car.service.IRoleService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class CarRealm extends AuthorizingRealm {
    @Autowired
    private IEmployeeService employeeService;
    @Autowired
    private IRoleService roleService;
    @Autowired
    private IPermissionService permissionService;

    //授权    将权限授予shiro,不是判断权限
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //获取当前登录主体对象
        Subject subject = SecurityUtils.getSubject();
        //获取主体的身份对象(这里获取的对象与认证方法doGetAuthenticationInfo返回的SimpleAuthenticationInfo对象的第一个参数是同一个参数)
        Employee employee = (Employee) subject.getPrincipal();
        //判断是否是超级管理员
//        if (employee.isAdmin()) {
//            info.addRole("admin");//方便后续可以直接用subject来判断是否管理员
//            info.addStringPermission("*:*");//权限通配符
//            return info;
//        }
        //根据用户的id查询该用户拥有的角色编码
        List<String> snList = roleService.selectSnByEmployeeId(employee.getId());
        info.addRoles(snList);
        //根据用户id查询该用户拥有的权限表达式
        List<String> expressionList = permissionService.selectExpressionByEmployeeId(employee.getId());
        info.addStringPermissions(expressionList);
        return info;//info对象中有哪些角色和权限,就代表当前登录用户拥有哪些角色和权限
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String clientUsername = (String) token.getPrincipal();
        Employee employee = employeeService.getByUserName(clientUsername);
        if (employee != null) {
            return new SimpleAuthenticationInfo(employee, employee.getPassword(), ByteSource.Util.bytes(employee.getName()) ,this.getName());
        } else {
            return null;
        }
    }

    @Autowired
    public void setCredentialsMatcher(CredentialsMatcher credentialsMatcher) {
        super.setCredentialsMatcher(credentialsMatcher);
    }
}
